package com.anjingsi.tools.encryption;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AESUtils {
    public AESUtils() {
    }
    public static String aesEncrypt(String content, String password) throws Exception {
        content = content != null ? content.replace("=", "") : "";
        if (password == null) {
            throw new Exception("Key为空null");
        } else if (password.length() != 16) {
            throw new Exception("Key长度不是16位");
        } else {
            byte[] raw = password.getBytes("utf-8");
            SecretKeySpec passwordSpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(1, passwordSpec);
            byte[] encrypted = cipher.doFinal(content.getBytes("utf-8"));
            return byte2HexStr(encrypted);
        }
    }

    private static String byte2HexStr(byte[] b) {
        StringBuilder sb = new StringBuilder();

        for(int i = 0; i < b.length; ++i) {
            String s = Integer.toHexString(b[i] & 255);
            if (s.length() == 1) {
                sb.append("0");
            }

            sb.append(s.toUpperCase());
        }

        return sb.toString();
    }

    public static String aesDecrypt(String content, String password) throws Exception {
        content = content != null ? content.replace("=", "") : "";
        if (password == null) {
            throw new Exception("Key为空null");
        } else if (password.length() != 16) {
            throw new Exception("Key长度不是16位");
        } else {
            byte[] raw = password.getBytes("utf-8");
            SecretKeySpec passwordSpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(2, passwordSpec);
            byte[] encrypted1 = str2ByteArray(content);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, "utf-8");
            return originalString;
        }
    }

    private static byte[] str2ByteArray(String s) {
        int byteArrayLength = s.length() / 2;
        byte[] b = new byte[byteArrayLength];

        for(int i = 0; i < byteArrayLength; ++i) {
            byte b0 = (byte)Integer.valueOf(s.substring(i * 2, i * 2 + 2), 16).intValue();
            b[i] = b0;
        }

        return b;
    }
}
